package com.funkids.prxis.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.funkids.common.Result;
import com.funkids.prxis.entity.SysSeckillGoods;
import com.funkids.prxis.entity.SysSeckillOrder;
import com.funkids.prxis.entity.SysUser;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author funkids
 * @since 2023-03-22
 */
@RestController
@RequestMapping("/prxis/sysSeckillGoods")
public class SysSeckillGoodsController extends BaseContoller implements InitializingBean {

    @PostMapping("/seckill")
    public Result seckill(Principal principal, @RequestBody Long goodsId){
        SysUser sysUser = sysUserService.getByUsername(principal.getName());
        if(sysUser==null){
            return Result.fail("请先登录！");
        }
        System.out.println(sysUser.getUserId()+"->"+goodsId);
        int tag = sysSeckillGoodsService.seckill(sysUser.getUserId(),goodsId);
        if(tag==0){
            return Result.fail("抱歉，秒杀商品已没有库存,秒杀失败！");
        }else if(tag==2){
            return Result.fail("抱歉，您只能购买一件该商品，秒杀失败！");
        }
        return Result.succ("正在秒杀中。。。");
    }

    @GetMapping("/getResult")
    public Result getResult(Principal principal, @RequestParam(name = "goodsId") Long goodsId){
        SysUser sysUser = sysUserService.getByUsername(principal.getName());
        Long tag = sysSeckillGoodsService.getResult(sysUser.getUserId(),goodsId);
        if(tag==0L){
            return Result.fail("秒杀失败");
        }else{
            System.out.println(tag);
            return Result.succ(tag);
        }
    }
    @Override
    public void afterPropertiesSet() throws Exception {
        List<SysSeckillGoods> list = sysSeckillGoodsService.list();
        if(CollectionUtils.isEmpty(list)){
            return;
        }
        list.forEach(goods->{
            redisUtil.set("GoodsId:"+goods.getGoodsId(),goods.getSeckillStock());
        });

    }
}

